<template>
  <div>
    <!-- 添加业务授权列表对话框 -->
    <el-dialog :title="config.titleFunc" :visible.sync="config.openFunc" width="750px" v-dialogDrag append-to-body>
      <el-form ref="formFunc" :model="formFunc" :rules="rulesFunc" :inline="true" label-width="160px">
        <el-row>
          <el-col>
            <el-form-item label="企业名称" prop="hbcClientAuthId"> <!-- 这里记录客户授权列表记录的ID，显示为其企业名称 -->
              <!-- <el-input v-model="formFunc.corporationName" placeholder="请输入企业名称" /> -->
              <el-select clearable
                v-model="formFunc.hbcClientAuthId"
                filterable
                placeholder="请选择"
                :disabled="config.hbcClientAuthIdFixed"
                @change="onHbcClientAuthIdChange"
              >
                <el-option v-for="item in hbcClientAuthList" :key="item.id" :label="item.corporationName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAddFuncProd"
              v-hasPermi="['hbcsupport:hbc-client-auth:create']"
              >添加</el-button>
          </el-col>
        </el-row>
        <el-row>
          <!-- 列表ip -->
          <el-table :data="formFunc.hbcClientAuthFunctionAuthList">
            <el-table-column label="序号" align="center" prop="no" >
              <template slot-scope="scope">{{scope.$index+1}}</template>
            </el-table-column>
            <!-- <el-table-column label="混合云客户授权管理id" align="center" prop="hbcClientAuthId" /> -->
            <el-table-column label="产品名称" align="center" prop="productName" />
            <el-table-column label="版本号" align="center" prop="productVersion" />
            <el-table-column label="产品数量" align="center" prop="productQuantity" />
            <el-table-column label="授权有效期" align="center" prop="authType" width="170">
              <template v-slot="scope">
                <span word>{{ scope.row.authType==1 ? parseTime(scope.row.authDurationBegin,'{y}.{m}.{d}')+' - '+parseTime(scope.row.authDurationEnd,'{y}.{m}.{d}'):'无限制' }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="授权有效期类型（0:无限制，1:指定范围）" align="center" prop="authType" /> -->
            <!-- <el-table-column label="授权有效期开始时间" align="center" prop="authDurationBegin" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.authDurationBegin) }}</span>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="授权有效期结束时间" align="center" prop="authDurationEnd" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.authDurationEnd) }}</span>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column> -->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template v-slot="scope">
                <el-button v-preventReClick size="mini" type="text" icon="el-icon-edit" @click="handleUpdateFuncProd(scope.$index, scope.row)"
                          v-hasPermi="['hbcsupport:hbc-client-auth:update']">修改</el-button>
                <el-button v-preventReClick size="mini" type="text" icon="el-icon-delete" @click="handleDeleteFuncProd(scope.$index, scope.row)"
                          v-hasPermi="['hbcsupport:hbc-client-auth:update']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick type="primary" @click="submitFormFunc">确 定</el-button>
        <el-button v-preventReClick @click="cancelFunc">取 消</el-button>
      </div>
    </el-dialog>

    <app-function-product-dialog
      :config="appFunctionProductDialogLicenseConfig"
      @on-submit="onSubmitFormFuncProduct"
      ref="appFunctionProdductDialogRef"
      >
    </app-function-product-dialog>
  </div>
</template>
<script>

import { getHbcClientAuthListAll } from "@/api/hbcsupport/hbcClientAuth";

import { getHbcClientAuthFunctionAuthPage, createOrUpdateHbcClientAuthFunctionAuthBatch} from "@/api/hbcsupport/hbcClientAuthFunctionAuth";

import AppFunctionProductDialog from "./app-function-product-dialog"

export default {
  props:{
    config:{
      openFunc:false,
      titleFunc:"",
      hbcClientAuthId:undefined,
      hbcClientAuthIdFixed:false,
      queryParams:{}
    }
  },
  components: {
    AppFunctionProductDialog
  },
  data() {
    return {
      hbcClientAuthList:[],
      //=== 添加业务授权
      titleFunc: "",
      formFunc:{
        hbcClientAuthId: undefined,
        hbcClientAuthFunctionAuthList: []
      },
      rulesFunc:{
        hbcClientAuthId: [{ pattern: /^[1-9]\d*$/, required: true, message: "企业不能为空", trigger: "blur" }],
      },

      appFunctionProductDialogLicenseConfig:{
        title:"",
        open:false,
        form:{
        }
      },
    }
  },
  created(){
    this.getHbcClientFunctionListAll(); // 业务授权列表
    this.getHbcClientAuthListAll();     // 业务授权列表表单中的下拉框
  },
  mounted() {

  },
  methods: {
    selectTime(data) {
      this.$nextTick(() => {
        this.$set(this.form, 'time', [data[0], data[1]]);
      });
    },
    // XXX TODO ,
    // 当修改时，为了防止选择授权客户下拉框而导致清空业务授权功能列表而误提交，在修改时禁止修改客户授权ID
    // 当新增时，可下拉选择，为防止误操作清空业务授权功能列表，这里当选择变化时，下面的业务授权列表进行刷新
    onHbcClientAuthIdChange(value){
      this.config.hbcClientAuthId=value;
      this.getHbcClientFunctionListAll();
    },
    //下拉选择授权客户列表
    getHbcClientAuthListAll(){
      getHbcClientAuthListAll({}).then(response => {
        this.hbcClientAuthList = response.data;
        // console.log("this.hbcClientAuthList:",this.hbcClientAuthList);
      });
    },
    getHbcClientFunctionListAll(){
      let self = this;
      const hbcClientAuthId = this.config.hbcClientAuthId;
      // XXX TODO，这里不分页，但是这里单页最大数据数量默认是100，当授权数量大于100条时，需要增加分页逻辑！！！
      getHbcClientAuthFunctionAuthPage({
        hbcClientAuthId:hbcClientAuthId,
        pageSize:100
      }).then(response => {
        self.formFunc = {
          hbcClientAuthId: hbcClientAuthId,
          hbcClientAuthFunctionAuthList: response.data.list
        };
      });
    },
    //==== 添加业务授权对话框
    resetFunc() {
      this.formFunc = {
        hbcClientAuthId: undefined,
        hbcClientAuthFunctionAuthList: []
      };
      this.resetForm("formFunc");
    },
    /** 删除按钮操作 */
    handleDeleteFunc(index, row) {
      let id = row.id;
      index = -1;
      // XXX TODO 查找一下，防止因为删除表格数据时引发的索引换乱和操作错误数据记录
      this.hbcClientAuthFunctionAuthList.forEach((item,idx)=>{
        if(item.id==id){
          index=idx;
        }
      });
      this.formFunc.hbcClientAuthFunctionAuthList.splice(index,1);
    },
    /** 提交按钮 */
    submitFormFunc() {
      // XXX TODO 这里通过查看方式打开的业务授权对话框时，企业id即授权id可能不是当前打开的页面的id！
      this.$refs["formFunc"].validate(valid => {
        if (!valid) {
          return;
        }
        // 添加的提交
        createOrUpdateHbcClientAuthFunctionAuthBatch(this.formFunc).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.config.openFunc = false;
        });

      });
    },
    cancelFunc(){
      this.config.openFunc = false;
      this.resetFunc();
    },

    //==== 添加业务授权对话框-添加产品对话框
    handleAddFuncProd(){
      this.$refs.appFunctionProdductDialogRef.reset();
      this.appFunctionProductDialogLicenseConfig.open = true;
      this.appFunctionProductDialogLicenseConfig.title = "新增产品";
      this.appFunctionProductDialogLicenseConfig.action = "add";
    },
    /** 修改按钮操作 */
    handleUpdateFuncProd(index, row) {
      this.$refs.appFunctionProdductDialogRef.reset();
      // XXX TODO 重新绑定，防止修改列表中的数据
      let formData = JSON.parse(JSON.stringify(row));
      let authDurationArr = [];
      if(formData.authDurationBegin){
        authDurationArr.push(new Date(formData.authDurationBegin));
      }
      if(formData.authDurationEnd){
        authDurationArr.push(new Date(formData.authDurationEnd));
      }
      formData.authDuration=authDurationArr;
      this.appFunctionProductDialogLicenseConfig.form = formData;
      this.appFunctionProductDialogLicenseConfig.open = true;
      this.appFunctionProductDialogLicenseConfig.title = "编辑产品";
      this.appFunctionProductDialogLicenseConfig.action = "update";
    },
    onSubmitFormFuncProduct(formData){
      if(this.appFunctionProductDialogLicenseConfig.action=="add"){ // add
        formData.id=(new Date()).getTime();
        formData.no=this.formFunc.hbcClientAuthFunctionAuthList.length+1;
        this.formFunc.hbcClientAuthFunctionAuthList.push(formData);
      }else{ // update
        let index = this.formFunc.hbcClientAuthFunctionAuthList.findIndex((value, index, arr) => {return value.id==formData.id})
        if(index!=-1){
          this.$set(this.formFunc.hbcClientAuthFunctionAuthList,index,formData);
        }
      }
    },
    /** 删除按钮操作 */
    handleDeleteFuncProd(index, row) {
      const id = row.id;
      index = this.formFunc.hbcClientAuthFunctionAuthList.findIndex((value, index, arr) => {return value.id==id})
      if(index!=-1){
        this.formFunc.hbcClientAuthFunctionAuthList.splice(index,1);
      };
    },

  }
}
</script>
